<template>
  <el-row>
    <el-col :span="12">
      <el-image src="/src/assets/images/login-bg-3.jpg"/>
    </el-col>
    <el-col :span="12">
      <el-form label-width="auto" style="max-width: 300px" class="loginForm">
        <h1>用户登录</h1>
        <el-form-item>
          <el-input v-model="regInfo.username" placeholder="请输入您的用户名" clearable suffix-icon="User"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="regInfo.password" placeholder="请输入您的密码" type="password" show-password clearable/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="regInfo.captchaInput" placeholder="请输入验证码" clearable
                    style="width: 170px;margin-right: 10px" suffix-icon="Checked"/>
          <el-image :src="imageBase64Data" @click="getCaptcha"/>
        </el-form-item>
        <el-form-item>
          <el-button type="success" class="loginBtn" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script setup>
import userApi from '@/api/userApi.js';
import {ref} from "vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {useTokenStore} from "@/stores/token.js";
import {useUserStore} from "@/stores/user.js";
const userStore = useUserStore();
const tokenStore = useTokenStore();
const router = useRouter();

//保存验证码
const imageBase64Data = ref("");

const regInfo = ref({
  username: '',
  password: '',
  key: '',
  captchaInput: '',
});

//获取验证码
function getCaptcha() {
  userApi.captcha()
      .then(resp => {
        regInfo.value.key = resp.data.key;
        //console.log(resp.data.captchaImageBase64Data)
        imageBase64Data.value = resp.data.imageBase64Data;
      })
}
//用户登录
function login() {
  userApi.login(regInfo.value)
      .then(resp => {
        if(resp.code == 10000){
          ElMessage.success(resp.msg);
          //保存token
          tokenStore.update(resp.data);
          //获取用户信息
          getInfo();
          //跳转到前台首页
          router.push('/user/index')
        } else {
          ElMessage.error(resp.msg);
        }
      })
}
getCaptcha()
//获取用户信息
function getInfo() {
  userApi.getInfo()
      .then(resp => {
        if (resp.code===10000){
          //将已登录用户的信息保存在Pinia中
          userStore.updateUser(resp.data);
        }


      })
}
</script>

<style scoped>
.loginForm {
  margin: 100px;
}

.loginForm h1 {
  text-align: center;
  margin-bottom: 20px;
}

.loginBtn {
  width: 100%;
}
</style>